package com.aaa.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @Author: YuXin
 * @Date : Created in 2020/11/6 15:16
 * @ClassName : IllegalCharFilter
 * @Description :
 * @Package_Name : com.aaa.zuulserver.filter
 */
@Component
public class IllegalCharFilter extends ZuulFilter {

    @Value("${illegalChar}")
    private String illegalChar;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() {
        //使用zuul包中提供的请求上下文对象请求的对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = currentContext.getRequest();
        //获取request对象
        HttpServletResponse response = currentContext.getResponse();
        //转换非法字符为数组
        String[] illegalCharList = illegalChar.split(",");
        //获取所有的参数列表
        Enumeration<String> parameterNames = request.getParameterNames();
        //循环参数  先判断有没有更多元素
        while (parameterNames.hasMoreElements()) {
            //获取参数的key  参数名
            String parameterName = parameterNames.nextElement();
            //获取参数的value  参数值
            String parameterValue = request.getParameter(parameterName);
            //循环非法字符
            for (String s : illegalCharList) {
                if (parameterValue.contains(s)) {
                    currentContext.setSendZuulResponse(false);
                    request.setCharacterEncoding("utf-8");
                    response.setCharacterEncoding("utf-8");
                    response.sendError(HttpStatus.SC_FORBIDDEN, "你的参数有不文明字符！");
                }
            }
        }
        return null;
    }
}
